package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;



@Aspect
@Component
@Slf4j
public class AutoFillAspect {

    @Pointcut("execution(* com.sky.service.*.*(..)) && @annotation(com.sky.annotation.AutoFill)")
    public void autoFillPointCut(){

    }

    @Before("autoFillPointCut()")
    public void autoFill(JoinPoint joinPoint) {
        log.info("开始自动填充公共字段----------------------------------------");

        try {
            // 1. 获取方法注解信息
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            AutoFill autoFill = signature.getMethod().getAnnotation(AutoFill.class);
            OperationType operationType = autoFill.value();

            // 2. 获取实体对象
            Object[] args = joinPoint.getArgs();
            if (args == null || args.length == 0) {
                return;
            }
            Object entity = args[0];

            // 3. 准备公共数据
            LocalDateTime now = LocalDateTime.now();
            Long currentUserId = BaseContext.getCurrentId();

            // 4. 根据操作类型使用反射调用setter方法
            if (operationType == OperationType.INSERT) {
                invokeSetter(entity, AutoFillConstant.SET_CREATE_TIME, now);
                invokeSetter(entity, AutoFillConstant.SET_CREATE_USER, currentUserId);
                invokeSetter(entity, AutoFillConstant.SET_UPDATE_TIME, now);
                invokeSetter(entity, AutoFillConstant.SET_UPDATE_USER, currentUserId);
            } else if (operationType == OperationType.UPDATE) {
                invokeSetter(entity, AutoFillConstant.SET_CREATE_TIME, now);
                invokeSetter(entity, AutoFillConstant.SET_CREATE_USER, currentUserId);
            }
        } catch (Exception e) {
            log.error("自动填充失败: {}", e.getMessage());
        }
    }

    /**
     * 通过反射调用对象的setter方法
     */
    private void invokeSetter(Object obj, String methodName, Object value) {
        try {
            Class<?> clazz = obj.getClass();
            // 根据参数类型获取方法
            Method method = clazz.getDeclaredMethod(methodName, value.getClass());
            method.invoke(obj, value);
        } catch (NoSuchMethodException e) {
            log.warn("方法 {} 不存在，跳过设置", methodName);
        } catch (Exception e) {
            log.error("调用方法 {} 失败: {}", methodName, e.getMessage());
        }
    }


}
